package com.zwl.android.aidoctor.util;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author tcmaiok.org
 */
public class MapSortUtil {

    public static List<Map.Entry<String, Double>> sortByValueList(HashMap<String, Double> hm) {
        // HashMap的entry放到List中
        List<Map.Entry<String, Double>> list
                = new LinkedList<Map.Entry<String, Double>>(hm.entrySet());

        //  对List按entry的value排序
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
            public int compare(Map.Entry<String, Double> o1,
                               Map.Entry<String, Double> o2) {
                return (o2.getValue()).compareTo(o1.getValue());//倒序
            }
        });

        return list;
    }

    //  hashmap按值排序
    public static HashMap<String, Double> sortByValue(HashMap<String, Double> hm) {
        // HashMap的entry放到List中
        List<Map.Entry<String, Double>> list
                = new LinkedList<Map.Entry<String, Double>>(hm.entrySet());

        //  对List按entry的value排序
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
            public int compare(Map.Entry<String, Double> o1,
                               Map.Entry<String, Double> o2) {
                return (o2.getValue()).compareTo(o1.getValue());//倒序
            }
        });

        // 将排序后的元素放到LinkedHashMap中
        HashMap<String, Double> temp = new LinkedHashMap<String, Double>();
        for (Map.Entry<String, Double> aa : list) {
            temp.put(aa.getKey(), aa.getValue());
        }
        return temp;
    }

    public static void main(String[] args) {
        HashMap<String, Double> hm = new HashMap<String, Double>();

        // 填充测试数据
        hm.put("Math", 98.6);
        hm.put("Data Structure", 98.19);
        hm.put("Database", 91.9);
        hm.put("Java", 95.1);
        hm.put("Operating System", 79.6);
        hm.put("Networking", 80.4);
        Map<String, Double> hm1 = sortByValue(hm);

        // 打印按值排序后的数据
        for (Map.Entry<String, Double> en : hm1.entrySet()) {
            System.out.println("Key = " + en.getKey()
                    + ", Value = " + en.getValue());
        }
    }

}

